package com.gyg.lockTest;

import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁情况下实现买票安全
 */
public class TestLock {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket).start();
        new Thread(buyTicket).start();
        new Thread(buyTicket).start();
    }
}

/**
 * 买票
 */
class BuyTicket implements Runnable {
    private int ticketNum = 100;
    private boolean flag = true;

    //定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (flag) {
            try {
                //加锁
                //TODO 注意：lock锁必须放置在try-finally的代码块中，且unlock方法放置在finally的第一行
                lock.lock();
                if (ticketNum <= 0) {
                    flag = false;
                } else {
                    //放大问题的发生性
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + "买到的票序号为：" + ticketNum--);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //解锁
                lock.unlock();
            }
        }
    }

}
